﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Engine.Graphics;

namespace Engine.Physics
{
    public class PolygonCollider : Collider
    {
        public Polygon Polygon
        {
            get { return Shape as Polygon; }
            private set { Shape = value; }
        }

        public PolygonCollider()
        {
        }

        public PolygonCollider(List<Vector2> _mesh)
        {
            Polygon = new Polygon(_mesh);
        }

        public override void Awake()
        {
            UpdatePolygon();
            base.Awake();
        }

        public override void LateUpdate(GameTime _gameTime)
        {
            base.LateUpdate(_gameTime);
            GraphicsEngine.Instance.DrawGizmo(GraphicsEngine.Instance.MainCamera.WorldToScreen(AABB), Color.Green);
            if (Polygon != null)
            {
                GraphicsEngine.Instance.DrawGizmo(Polygon.Points);
                GraphicsEngine.Instance.DrawGizmo(Polygon.GetMidpoint());
            }
        }

        public override void UpdateShape()
        {
            base.UpdateShape();
            UpdatePolygon();
        }

        public override void RecalcShape()
        {
            base.RecalcShape();
            UpdatePolygon();
        }

        public void UpdatePolygon()
        {
            if (Polygon != null)
                Polygon.Update(Position, gameObject.transform.Rotation);
        }

        public override void RecalcAABB()
        {
            mAABB = RecalcAABBFromPoly();
            aabbLocation = new Vector2(mAABB.Location.X, mAABB.Location.Y);
        }

        private Rectangle RecalcAABBFromPoly()
        {
            float minX = float.MaxValue;
            float maxX = float.MinValue;
            float minY = float.MaxValue;
            float maxY = float.MinValue;

            for (int i = 0; i < Polygon.Points.Count; i++)
            {
                if (Polygon.Points[i].X < minX)
                    minX = Polygon.Points[i].X;
                if (Polygon.Points[i].X > maxX)
                    maxX = Polygon.Points[i].X;

                if (Polygon.Points[i].Y < minY)
                    minY = Polygon.Points[i].Y;
                if (Polygon.Points[i].Y > maxY)
                    maxY = Polygon.Points[i].Y;
            }

            return new Rectangle((int)minX, (int)minY, (int)(maxX - minX), (int)(maxY - minY));
        }
    }
}
